package com.myproject.myblogserver.service.impl;

import com.myproject.myblogserver.dto.blog.BlogPreviewDto;
import com.myproject.myblogserver.dto.blog.BlogUploadDto;
import com.myproject.myblogserver.entity.Blog;
import com.myproject.myblogserver.entity.BlogTag;
import com.myproject.myblogserver.mapper.BlogMapper;
import com.myproject.myblogserver.mapper.BlogTagMapper;
import com.myproject.myblogserver.service.IBlogService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 博客表 服务实现类
 * </p>
 *
 * @author jiangweike
 * @since 2025-01-12
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    BlogMapper blogMapper;

    @Autowired
    BlogTagMapper blogTagMapper;

    public Blog saveBlog(BlogUploadDto blogUploadDto, Long userId) {
        var blog = new Blog();
        blog.setTitle(blogUploadDto.getTitle());
        blog.setAuthorId(userId);
        blog.setSummary(blogUploadDto.getSummary());
        blog.setContent(blogUploadDto.getContent());

        blogMapper.insert(blog);

        if (blogUploadDto.getTags() != null)
            for (var tag : blogUploadDto.getTags()) {
                var blogTag = new BlogTag();
                blogTag.setBlogId(blog.getId());
                blogTag.setTagName(tag);
                blogTagMapper.insert(blogTag);
            }
        return blog;
    }

    public Page<BlogPreviewDto> searchBlogs(List<String> keyword, Page<BlogPreviewDto> page) {
        var result = blogMapper.searchBlogs(page, keyword);
        result.getRecords().forEach(dto -> {
            if (dto.getTagsStr() != null) {
                List<String> tags = Arrays.stream(dto.getTagsStr().split(","))
                        .collect(Collectors.toCollection(ArrayList::new));
                dto.setTags(tags);
            }
        });
        return result;
    }
}
